﻿using System;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Command;
using Rio.Framework.Pages.Controls.Models;

namespace Rio.Framework.Pages.Controls.BaseClass
{
    public class ListboxBase : ControlBase
    {

        private RelayCommand<string> _selectedCommand;

        public event EventHandler ItemSelectionChanged;
        protected void RaiseItemSelectionChanged()
        {
            if (ItemSelectionChanged != null)
                ItemSelectionChanged(this, new EventArgs());
        }

        /// <summary>
        /// Gets the selected command.
        /// </summary>
        /// <value>The selected command.</value>
        public RelayCommand<string> SelectedCommand
        {
            get
            {
                return _selectedCommand;
            }
        }

        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <value>The items.</value>
        public ObservableCollection<ISelectableItem<object>> Items
        {
            get
            {
                ObservableCollection<ISelectableItem<object>> viewModel = this.DataContext as ObservableCollection<ISelectableItem<object>>;

                if (viewModel == null)
                {
                    viewModel = new ObservableCollection<ISelectableItem<object>>();

                    this.DataContext = viewModel;
                }

                return viewModel;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ListboxBase" /> class.
        /// </summary>
        public ListboxBase()
        {
            _selectedCommand = new RelayCommand<string>(OnSelectedActionPerformed);
        }

        /// <summary>
        /// Clears the selection.
        /// </summary>
        public void ClearSelection()
        {
            foreach (var item in Items)
            {
                item.IsSelected = false;
            }
        }

        /// <summary>
        /// Called when [selected action performed].
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void OnSelectedActionPerformed(string parameter)
        {
            RaiseItemSelectionChanged();
        }

    }
}
